<?php

namespace Client\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

// <-- Add this import
use Client\Model\Client;
use Client\Form\ClientForm;
use Client\Form\ClientQueryForm;

class ClientController extends AbstractActionController
{
    protected $clientTable;
    protected $accountTable;
    protected $clients;
    protected $payment;
    protected $check_profit;
    protected $thrift_profit;
    protected $account_profit;
    protected $account_profit_maximum;
    protected $account_profit_minimum;
    protected $check_balance;
    protected $thrift_balance;
    protected $account_balance;

    /**
     * @return array|object
     */
    public function getClientTable()
    {
        if (!$this->clientTable) {
            $sm = $this->getServiceLocator();
            $this->clientTable = $sm->get('Client\Model\ClientTable');
        }
        return $this->clientTable;
    }

    /**
     * @return array|object
     */
    public function getAccountTable()
    {
        if (!$this->accountTable) {
            $sm = $this->getServiceLocator();
            $this->accountTable = $sm->get('Account\Model\AccountTable');
        }
        return $this->accountTable;
    }

    /**
     * 计算某一客户利润
     * @param string $client_id 客户号
     */
    public function setAccountProfitByClientId($client_id)
    {
        $this->payment = 0;
        $this->check_profit = 0;
        $this->thrift_profit = 0;
        $this->account_profit = 0;
        $this->check_balance = 0;
        $this->thrift_balance = 0;
        $this->account_balance = 0;
        $this->check = $this->getAccountTable()->getCheckByClientId($client_id);
        $this->thrift = $this->getAccountTable()->getThriftByClientId($client_id);
        $this->account = $this->getAccountTable()->getAccountByClientId($client_id);
        foreach ($this->check as $key => $check) {
            $this->payment += $check['account_balance'];
            $this->check_profit += $check['account_balance'] * $check['rate'];
            $this->check_balance += $check['overdraft'] - $check['account_balance'];
        }
        foreach ($this->thrift as $key => $thrift) {
            $this->thrift_profit += $thrift['account_balance'] * $thrift['rate'];
            $this->thrift_balance += $thrift['account_balance'];
        }
        $this->account_profit = $this->check_profit + $this->thrift_profit;
        $this->account_balance = $this->check_balance + $this->thrift_balance;
    }

    /**
     * 计算所有客户利润
     * @return $this
     */
    public function setAccountProfit()
    {
        $this->account_profit_maximum = PHP_FLOAT_MIN;
        $this->account_profit_minimum = PHP_FLOAT_MAX;
        foreach ($this->clients as $key => $client) {
            $this->setAccountProfitByClientId($client['client_id']);
            $this->clients[$key]['account_profit'] = round($this->account_profit,4);
            if ($this->account_profit_maximum < $this->account_profit) $this->account_profit_maximum = $this->account_profit;
            if ($this->account_profit_minimum > $this->account_profit) $this->account_profit_minimum = $this->account_profit;
        }
        return $this;
    }

    /**
     * 设置客户星级
     * @return $this
     */
    public function setStarLevel()
    {
        $layer = 5;     //  5个层级
        $range = $this->account_profit_maximum - $this->account_profit_minimum;     //  极差
        $hash = $range / $layer;    //  每个区间的组内差
        foreach ($this->clients as $key => $client) {       //  轮询每个客户
            $grade = $client['account_profit'] - $this->account_profit_minimum;     //  相对利润=客户利润-所有客户中的最小利润
            $level = $grade / $hash;    //  星级=相对利润/组内差
            $this->clients[$key]['star_level'] = intval(ceil($level));      //  向上取整，用intval函数转换为整型
        }
        return $this;
    }

    /**
     * 初始化页面渲染
     * @return array|ViewModel
     */
    public function indexAction()
    {
        $form = new ClientQueryForm();
        $column = $this->params()->fromQuery('column', null);
        $parame = $this->params()->fromQuery('parame', null);
        $paging = $this->params()->fromQuery('paging', 0);
        $limit = 10;    //每页显示记录数目
        $offset = $limit * intval($paging);     //第几页-1
        $this->clients = $this->getClientTable()->findClient($column, $parame, $offset, $limit);
        $this->setAccountProfit()->setStarLevel();
        $view = new ViewModel(array(
            'form' => $form,
            'column' => $column,
            'parame' => $parame,
            'clients' => $this->clients
        ));
        return $view;
    }

    // Add content to this method
    public function addAction()
    {
        $form = new ClientForm();
        $form->get('submit')->setAttribute('value', '确定')->setAttribute('class', 'btn btn-primary');
        if ($this->getRequest()->isPost()) {
            $client = new Client();
            //$form->bind($client);
            $form->setInputFilter($client->getInputFilter());
            $form->setData($this->getRequest()->getPost());
            if ($form->isValid()) {
                $client->exchangeArray($form->getData());
                $this->getClientTable()->saveClient($client);
                // Redirect to list of clients
                return $this->redirect()->toRoute('client');
            }
        }
        return array('form' => $form);
    }

    // Add content to this method
    public function editAction()
    {
        $client_id = $this->params()->fromRoute('id', null);
        if (is_null($client_id)) return $this->redirect()->toRoute('client', array('action' => 'add'));
        // if it cannot be found, in which case go to the index page
        try {
            $client = $this->getClientTable()->getClient($client_id);
        } catch (\Exception $ex) {
            return $this->redirect()->toRoute('client', array('action' => 'index'));
        }
        $form = new ClientForm();
        $form->bind($client);
        $form->get('submit')->setAttribute('value', '确定')->setAttribute('class', 'btn btn-primary');
        if ($this->getRequest()->isPost()) {
            $form->setInputFilter($client->getInputFilter());
            $form->setData($this->getRequest()->getPost());
            if ($form->isValid()) {
                $result = $this->getClientTable()->setClient($client);
                // Redirect to list of clients
                return $this->redirect()->toRoute('client');
            }
        }
        return array(
            'client_id' => $client_id,
            'form' => $form
        );
    }

    // Add content to the following method
    public function deleteAction()
    {
        $client_id = $this->params()->fromRoute('id', null);
        if (is_null($client_id)) return $this->redirect()->toRoute('client', array('action' => 'delete'));
        if ($this->getRequest()->isPost()) {
            if ($this->getRequest()->getPost('del', 'No') == 'Yes') {
                $client_id = $this->getRequest()->getPost('client_id');
                $this->getClientTable()->deleteClient($client_id);
            }
            return $this->redirect()->toRoute('client');
        }
        return array(
            'client_id' => $client_id,
            'client' => $this->getClientTable()->getClient($client_id)
        );
    }

    public function sortAction()
    {
        $sort_id = null;
        $this->clients = $this->getClientTable()->findClient();
        $this->setAccountProfit()->setStarLevel();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $sort_id = $request->getPost();
            $profit = array_column($this->clients, 'account_profit');
            $id = intval($sort_id['id']);
            switch ($id) {
                case 1:
                    array_multisort($profit, SORT_ASC, $this->clients);
                    break;
                case 2:
                    array_multisort($profit, SORT_DESC, $this->clients);
                    break;
            }
        }
        $response = $this->getResponse();
        $response->setContent(json_encode($this->clients));
        return $response;
    }

}